package com.bxji.spring.ms.geteway;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

/**
 * @author bxji <br/>
 * 
 *         zuul提供了fallback机制，我们可以给断路配置一个自定义回退。
 */
@Component
public class MyZuulFallBack implements ZuulFallbackProvider {

    /**
     * getRoute方法，告诉Zuul它是负责哪个route定义的熔断(大小写敏感，与映射配置一致)。
     * 
     */
    @Override
    public String getRoute() {
        return "msec-provider";
    }

    /**
     * fallbackResponse方法，告诉 Zuul 断路出现时，它会提供一个什么返回值来处理请求。
     */
    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.BAD_REQUEST;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.BAD_REQUEST.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.BAD_REQUEST.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            /*
             * 当服务出现异常时，打印相关异常信息，
             * 并返回"The service is unavailable，happened error! provider-user"。
             */
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(
                        (" The service is unavailable，happened error!" + getRoute()).getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }

}
